package com.sinoglobal.ningxia.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.sinoglobal.networkconnections.ResultCallback;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.MyCollectionActivity;
import com.sinoglobal.ningxia.activity.news.NewsDetailActivity;
import com.sinoglobal.ningxia.adapter.NewsAdapter;
import com.sinoglobal.ningxia.beans.MyCollectionNewsBean;
import com.sinoglobal.ningxia.beans.MyCollectionRefreshVo;
import com.sinoglobal.ningxia.beans.NewsBean;
import com.sinoglobal.ningxia.dialog.DialogBuilder;
import com.sinoglobal.ningxia.dialog.MDialogMethod;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.thread.ItktOtherAsyncTask;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.ToastBuilder;

import java.util.List;

/**
 * @author wxy
 * @createdate 2014-6-17 上午9:22:00
 * @Description: 我的收藏--新闻
 */
public class MyCollectionNewsFragment extends Fragment {

    private View view;// 整个新闻界面的view
    public static Handler myCollectionNewsFragmentHandler;
    private final int TAB_NEWS = 0;// 新闻
    //    private ArrayList<MyCollectionItemVo> myCollectionDataVo;// 用来显示新闻列表的data
    private ListView myCollectionCateListView;// 该界面的listview
    private ProgressDialog pd;
    private TextView myCollectionNoDataShow;// 当该收藏为空的时候，将这个textview提示给用户
    public static Handler handler;
    private NewsAdapter newsAdapter;
    private List<NewsBean> newsBeanList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Auto-generated method stub
        view = LayoutInflater.from(getActivity()).inflate(R.layout.my_collection_cate, null);
        init();// 初始化控件
        addListener();// 添加点击事件
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        loadCollectionList();
                        break;

                    default:
                        break;
                }
            }
        };
        return view;
    }

    private void addListener() {
        // 长按删除该条收藏
        myCollectionCateListView.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
                Logger.i("在我的收藏新闻长按事件");
                final DialogBuilder dialogBuilder = new DialogBuilder(getActivity());
                // 选择dialogBuilder中有两个button的构造方法
                dialogBuilder.Dialogbtn2(getString(R.string.sure_to_del_collect), R.layout.dialog_two_button, new MDialogMethod() {

                    @Override
                    public void dialogOk() {
                        //向服务器告知所删除的item
                        new ItktOtherAsyncTask<Void, Void, MyCollectionRefreshVo>(true) {

                            @Override
                            public MyCollectionRefreshVo before(Void... params) throws Exception {
                                // “type” //收藏类型 1娱乐 2美食 3新闻 4栏目 5安居
                                // ‘action’:1|2 1代表添加收藏2代表删除收藏
                                return RemoteImpl.getInstance().deleteMyCollection(FlyApplication.userId, "3", "2", newsBeanList.get(position).getId());
                            }

                            @Override
                            public void after(MyCollectionRefreshVo result) {
                                if (result != null) {
                                    if (Code.CODE_SUCCESS != result.getCode()) {
                                        ToastBuilder.getIntance(FlyApplication.context).showToast(result.getMessage());
                                        dialogBuilder.mdialog.dismiss();
                                    } else {
                                        ToastBuilder.getIntance(FlyApplication.context).showToast(result.getMessage());
                                        FlyApplication.myCollectionTabNewsNum = result.getCounts();
                                        if (MyCollectionActivity.myCollectionTabTextNumHandler != null) {
                                            MyCollectionActivity.myCollectionTabTextNumHandler.sendEmptyMessage(TAB_NEWS);
                                        }
//                                        myCollectionDataVo.remove(position);
//                                        myCollectionAdapter.notifyDataSetChanged();
                                        newsBeanList.remove(position);
                                        newsAdapter.notifyDataSetChanged();
                                        dialogBuilder.mdialog.dismiss();
                                    }
                                }
                            }

                            @Override
                            public void exception() {
                                //Auto-generated method stub
                            }
                        }.execute();

                    }

                    @Override
                    public void dialogCancel() {
                        dialogBuilder.mdialog.dismiss();
                    }
                });

                return true;
            }
        });
        // 点击某一项查看收藏的详情
        myCollectionCateListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
                Logger.i("在我的收藏新闻点击事件");
                Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                // 只需要传一个新闻的id
                NewsBean newsBean = new NewsBean();
                newsBean.setId(newsBeanList.get(position).getId());
                intent.putExtra(FlyApplication.isFromCollection, "1");
                intent.putExtra(NewsBean.class.getCanonicalName(), newsBean);
                FlyUtil.intentForward(getActivity(), intent);
                getActivity().finish();
            }
        });

    }

    @SuppressLint("HandlerLeak")
    private void init() {
        // 显示新闻列表
        myCollectionNoDataShow = (TextView) view.findViewById(R.id.my_collection_no_data_show);
        myCollectionCateListView = (ListView) view.findViewById(R.id.my_collection_cate_listView);
//        if (null != myCollectionAdapter) {
//            myCollectionCateListView.setAdapter(myCollectionAdapter);
//            return;
//        }
        if (null != newsAdapter) {
            myCollectionCateListView.setAdapter(newsAdapter);
            return;
        }
        loadCollectionList();

    }

    private void loadCollectionList() {
//        new AsyncTask<Void, Void, MyCollectionDataVo>() {
//            protected void onPreExecute() {
//                pd = new ProgressDialog(getActivity());
//            }
//
//            ;
//
//            @Override
//            protected MyCollectionDataVo doInBackground(Void... params) {
//                try {
//                    return RemoteImpl.getInstance().getMyCollectionDataVo(FlyApplication.userId, "3", "0", "10");
//                } catch (Exception e) {
//                    //Auto-generated catch block
//                    e.printStackTrace();
//                }
//                return null;
//            }
//
//            protected void onPostExecute(MyCollectionDataVo result) {
//                pd.dismiss();
//                if (result != null) {
//                    if (Code.CODE_SUCCESS != result.getCode()) {
//                        myCollectionNoDataShow.setVisibility(View.VISIBLE);
//                    } else {
//                        if (result.getList().size() == 0) {
//                            myCollectionNoDataShow.setVisibility(View.VISIBLE);
//                        } else {
//                            myCollectionNoDataShow.setVisibility(View.GONE);
//                            ItktLog.i("MyCollectionNewsFragment=========呗初始化了");
//                            myCollectionDataVo = result.getList();
//                            FlyApplication.myCollectionTabNewsNum = result.getCol_num();
//                            myCollectionAdapter = new MyCollectionAdapter(myCollectionDataVo, getActivity(), "3");
//                            myCollectionCateListView.setAdapter(myCollectionAdapter);
//                        }
//                    }
//                } else {
//                    myCollectionNoDataShow.setVisibility(View.VISIBLE);
//                }
//            }
//
//            ;
//        }.execute();
        pd = new ProgressDialog(getActivity());
        ResultCallback resultCallback = new ResultCallback(getActivity()) {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                MyCollectionNewsBean myCollectionNewsBean = null;
                try {
                    myCollectionNewsBean = JSON.parseObject(response, MyCollectionNewsBean.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                pd.dismiss();
                if (myCollectionNewsBean != null) {
                    if (Code.CODE_SUCCESS != myCollectionNewsBean.getCode()) {
                        myCollectionNoDataShow.setVisibility(View.VISIBLE);
                    } else {
                        if (myCollectionNewsBean.getList().size() == 0) {
                            myCollectionNoDataShow.setVisibility(View.VISIBLE);
                        } else {
                            myCollectionNoDataShow.setVisibility(View.GONE);
                            ItktLog.i("MyCollectionNewsFragment=========呗初始化了");
                            newsBeanList = myCollectionNewsBean.getList();
//                            myCollectionDataVo = myCollectionNewsBean.getList();
                            FlyApplication.myCollectionTabNewsNum = myCollectionNewsBean.getCol_num() + "";
                            newsAdapter = new NewsAdapter(getActivity(), newsBeanList, false);
//                            myCollectionAdapter = new MyCollectionAdapter(myCollectionDataVo, getActivity(), "3");
                            myCollectionCateListView.setAdapter(newsAdapter);
                        }
                    }
                } else {
                    myCollectionNoDataShow.setVisibility(View.VISIBLE);
                }

            }


        };
        RemoteImpl.getInstance().getMyCollectionNews(this, FlyApplication.userId, 0).execute(resultCallback);
    }
}
